package com.jackson.passjava.multi.component;

import com.jackson.passjava.account.entity.AccountEntity;
import com.jackson.passjava.common.utils.R;
import com.jackson.passjava.common.utils.ResultUtil;
import com.jackson.passjava.multi.feign.*;

import com.jackson.passjava.order.entity.OrderEntity;
import com.jackson.passjava.storage.entity.StorageEntity;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/8/24 17:33
 */
@Component
@Slf4j
public class TestRollback {

    final OrderFeign orderFeign;
    final StorageFeign storageFeign;
    final AccountFeign accountFeign;

    @Autowired
    public TestRollback(OrderFeign orderFeign,StorageFeign storageFeign,AccountFeign accountFeign) {
        this.orderFeign = orderFeign;
        this.storageFeign = storageFeign;
        this.accountFeign = accountFeign;
    }


    @GlobalTransactional(rollbackFor = Exception.class)
    public void testRollBack() throws Exception {
        log.info("seata分布式事务Id:{}",RootContext.getXID());

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setCount(2);
        orderEntity.setMoney(new BigDecimal(10));
        orderEntity.setUserid(1);
        orderEntity.setProductid(1);
        orderEntity.setStatus(0);
        orderFeign.save(orderEntity);
        R storageInfo = storageFeign.info(1);

        StorageEntity storage = ResultUtil.convertToJavaBean(storageInfo.get("storage"),StorageEntity.class);
        storage.setUsed(storage.getUsed() + 10);
        storage.setResidue(storage.getResidue() - 10);

//        R accountInfo = accountFeign.info(1);
//        AccountEntity accountEntity = ResultUtil.convertToJavaBean(accountInfo.get("account"),AccountEntity.class);
//        BigDecimal bigDecimal = accountEntity.getUsed().add(new BigDecimal(10));
//        accountEntity.setUsed(bigDecimal);
//        BigDecimal subtract = accountEntity.getResidue().subtract(new BigDecimal(10));
//        accountEntity.setResidue(subtract);
//
//        accountFeign.update(accountEntity);


        storageFeign.update(storage);
        String res = null;
      //  System.out.println(res.toString());

    }

}
